package org.qloudgen.borg.cluster.operator;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.qloudgen.borg.CommonValues;
import org.qloudgen.borg.beans.Cluster;
import org.qloudgen.borg.metadb.DefaultImpl;
import org.qloudgen.borg.utils.RemoteShellExec;

public abstract class AbstractClusterOperator implements IClusterOperator{

	static Log log = LogFactory.getLog(AbstractClusterOperator.class);
	
	protected Cluster cluster;
	protected String operatorType;
	protected RemoteShellExec exec;
	
	public AbstractClusterOperator(Cluster cluster, String operatorType){
		this.setCluster(cluster);
		this.setOperatorType(operatorType);
		exec = new RemoteShellExec(cluster.getMasterIp(),cluster.getSysUser(),cluster.getSysUserPassword());
	}
	
	public int handler(){
		
		// result
		// 0: success
		// -1 : failure
		int result = 0;
		
		try {
			exec.login();
		} catch (IOException e) {
			log.error(e.getMessage());
			return -1;
		}
		
		int flag = CommonValues.clusterOperators.get(operatorType);
		
		switch (flag) {
			case 1 : result = start(); break;
			case 2 : result = stop();break;
			case 3 : result = pause();break;
			case 4 : result = add();break;
			case 5 : result = remove();break;
			case 6 : result = delete();break;
			case 7 : result = uploadJar();break;
		}
		
		exec.close();
		
		return result;
		
	}

	@Override
	public int delete() {
		return delete(this.getCluster());
	}
	
	public int delete(Cluster cluster) {
		
		DefaultImpl.deleteClusterID(cluster.getClusterID());
		return 0;
	}

	@Override
	public int pause() {
		return pause(this.getCluster());
	}
	
	public int pause(Cluster cluster) {
		
		cluster.setIsAvailable(cluster.getIsAvailable().equals("y")?"n":"y");
		DefaultImpl.updateClusterAvailable(cluster);
		return 0;
	}

	public String getOperatorType() {
		return operatorType;
	}

	public void setOperatorType(String operatorType) {
		this.operatorType = operatorType;
	}

	public Cluster getCluster() {
		return cluster;
	}

	public void setCluster(Cluster cluster) {
		this.cluster = cluster;
	}

	public RemoteShellExec getExec() {
		return exec;
	}

	public void setExec(RemoteShellExec exec) {
		this.exec = exec;
	}
	
	public abstract int uploadJar();

}
